package com.example.choupaiapp.main.activity.home;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.DateFormatUtil;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.GsonUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.common.view.XListView;
import com.example.choupaiapp.main.activity.mine.ReportActivity;
import com.example.choupaiapp.main.bean.CommentListBean;
import com.example.choupaiapp.main.bean.CommentRemindJsonBean;
import com.example.choupaiapp.main.bean.RemindJson;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.util.DetailCommentDialog;
import com.example.choupaiapp.main.util.DialogFragmentDataCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.shuyu.textutillib.RichTextView;
import com.shuyu.textutillib.SmileUtils;
import com.shuyu.textutillib.listener.SpanAtUserCallBack;
import com.shuyu.textutillib.model.UserModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by ASUS on 2019/11/20.
 */

public class CommentDetailActivity extends CommonActivity implements OnRefreshLoadMoreListener, DialogFragmentDataCallback {

    @BindView(R.id.head_photo)
    CircleImageView headPhoto;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.name)
    TextView name_tv;
    @BindView(R.id.content)
    RichTextView content_tv;
    @BindView(R.id.praise)
    TextView praise;
    @BindView(R.id.comment)
    TextView comment;
    @BindView(R.id.receive_listview)
    XListView receiveListview;
    @BindView(R.id.detail_more)
    LinearLayout detail_more;
    private String contentId;
    private String replyCommentId;
    private String name;
    private String content;
    private String timeTv;
    private String head;
    private String praiseNum;
    private String commentNum;
    private int pageNum = 1;
    private int pageSize = 10;
    private QuickAdapter<CommentListBean.PageBean.ListBean> quickAdapter;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.image)
    CircleImageView image;
    private String userId;
    private String isLike;
    private Drawable drawable_select;
    private Drawable drawable_unselect;
    @BindView(R.id.comment_rl)
    RelativeLayout comment_rl;
    @BindView(R.id.comment_et)
    RichTextView comment_et;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.view_line)
    View view_line;
    private String replyUserId;
    private String replyCommentId_;
    private UserInfoBean mUserInfoBean;
    private String content_anonymity;
    private String content_userid;
    private String id;
    private String module;
    private String replayName = "";
    private String replayContent = "";
    private List<UserModel> nameList;
    private int weight = 0;
    private CommentRemindJsonBean commentRemindJsonBean;

    SpanAtUserCallBack spanAtUserCallBack = new SpanAtUserCallBack() {
        @Override
        public void onClick(View view, UserModel userModel1) {
            Bundle bundle = new Bundle();
            bundle.putString("userId", userModel1.getUser_id());
            bundle.putString("userName", userModel1.getUser_name());
            startActivity(OtherInfoActivity.class, bundle);
            if (view instanceof TextView) {
                ((TextView) view).setHighlightColor(Color.TRANSPARENT);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_detail);
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.equals("CommentDetailActivity_comment")) {
            showDialog(context, "评论中...");
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            try {
                for (int i = 0; i < comment_et.getNameList().size(); i++) {
                    JSONObject userJson = new JSONObject();
                    userJson.put("userId", comment_et.getNameList().get(i).getUser_id());
                    userJson.put("nickname", comment_et.getNameList().get(i).getUser_name());
                    jsonArray.put(userJson);
                }
                jsonObject.put("remindJson", jsonArray.toString());
                jsonObject.put("contentId", contentId);
                jsonObject.put("comment", comment_et.getText().toString().trim());
                jsonObject.put("replyUserId", replyUserId);
                jsonObject.put("replyCommentId", replyCommentId_);
                jsonObject.put("position", 2);
                if (!TextUtils.isEmpty(module) && "2".equals(module)) {
                    jsonObject.put("type", 2);
                } else {
                    jsonObject.put("type", 1);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.COMMENT_SAVE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                @Override
                public void onSuccess(SendCodeBean sendCodeBean) {
                    dismissDialog();
                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                        replyCommentId_ = replyCommentId;
                        replayContent = "";
                        comment.setText(Integer.parseInt(comment.getText().toString()) + 1 + "");
                        EventBus.getDefault().post("comment_detial_add:" + "comment");
                        EventBus.getDefault().post("comment_detial_add_home:" + contentId);
//                        EventBus.getDefault().post("commentDetail_refresh");
                        List<CommentListBean.PageBean.ListBean> commentList = new ArrayList<>();
                        for (int i = 0; i < quickAdapter.getCount(); i++) {
                            commentList.add(quickAdapter.getItem(i));
                        }
                        CommentListBean.PageBean.ListBean bean = new CommentListBean.PageBean.ListBean();
                        bean.setId(sendCodeBean.getCommentId());
                        bean.setComment(comment_et.getText().toString().trim());
                        bean.setContentId(Integer.parseInt(contentId));
                        bean.setPosition(2);
                        if (!TextUtils.isEmpty(module) && "2".equals(module)) {
                            bean.setType(2);
                        } else {
                            bean.setType(1);
                        }
                        bean.setRemindJson(jsonArray.toString());
                        bean.setCreateTime(DateFormatUtil.ms4Date(System.currentTimeMillis()));
                        bean.setAvatar(mUserInfoBean.getUser().getAvatar());
                        bean.setNickname(mUserInfoBean.getUser().getNickname());
                        bean.setReplyNickname(replayName);
                        bean.setUserId(mUserInfoBean.getUser().getUserId());
                        bean.setReplyUserId(Integer.parseInt(replyUserId));
                        quickAdapter.clear();
                        quickAdapter.add(bean);
                        quickAdapter.addAll(commentList);
                        replyUserId = userId;
                        comment_et.setText("");
                        replayName = "";
                        scrollView.scrollTo(0, view_line.getTop());
                    } else {
                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                        } else {
                            showImageToas(sendCodeBean.getMsg());
                        }
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    dismissDialog();
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 处理自己的表情
     */
    private void initEmoji() {
        List<Integer> data = new ArrayList<>();
        List<String> strings = new ArrayList<>();
        int resofficial = getResources().getIdentifier("icon_comment_official", "mipmap", getPackageName());
        int resgod = getResources().getIdentifier("icon_comment_god", "mipmap", getPackageName());
        data.add(resofficial);
        strings.add("[icon_comment_official]");
        data.add(resgod);
        strings.add("[icon_comment_god]");
        /**初始化为自己的**/
        SmileUtils.addPatternAll(SmileUtils.getEmoticons(), strings, data);
    }

    @Override
    protected void initView() {
        setTitle("评论详情");
        EventBus.getDefault().register(this);

        drawable_select = getResources().getDrawable(R.mipmap.icon_praise_select);
        drawable_unselect = getResources().getDrawable(R.mipmap.item_praise);

        initEmoji();

        mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        if (mUserInfoBean != null) {
            Glide.with(context)
                    .load(mUserInfoBean.getUser().getAvatar() + Config.IMAGE_LIM)
                    .error(R.mipmap.icon_no_head)
                    .into(image);
        } else {
            Glide.with(context)
                    .load(R.mipmap.icon_no_head)
                    .error(R.mipmap.icon_no_head)
                    .into(image);
        }

        nameList = new ArrayList<>();
        //直接使用RichTextView
        comment_et.setAtColor(Color.parseColor(getString(R.string.remind_color)));
        comment_et.setLinkColor(Color.BLUE);
        //所有配置完成后才设置text
        comment_et.setNameList(nameList);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            contentId = bundle.getString("contentId");
            id = bundle.getString("id");
            module = bundle.getString("module");
            content_userid = bundle.getString("content_userid");
            content_anonymity = bundle.getString("content_anonymity");
            userId = bundle.getString("userId");
            replyCommentId = bundle.getString("replyCommentId");
            name = bundle.getString("name");
            content = bundle.getString("content");
            timeTv = bundle.getString("time");
            head = bundle.getString("head");
            praiseNum = bundle.getString("praise");
            commentNum = bundle.getString("commentNum");
            isLike = bundle.getString("isLike");
            weight = bundle.getInt("weight");

            commentRemindJsonBean = (CommentRemindJsonBean) bundle.getSerializable("commentRemindJsonBean");

            replyUserId = userId;
            replyCommentId_ = replyCommentId;

            if (content_userid.equals(userId)) {
                if ("1".equals(content_anonymity)) {
                    Glide.with(context)
                            .load(R.mipmap.head_anonymous_orange)
                            .dontAnimate()
                            .placeholder(R.mipmap.icon_no_head)
                            .into(headPhoto);
                    name_tv.setText("匿名用户");
                } else {
                    Glide.with(context)
                            .load(head + Config.IMAGE_LIM)
                            .dontAnimate()
                            .placeholder(R.mipmap.icon_no_head)
                            .into(headPhoto);
                    name_tv.setText(name);
                }
            } else {
                Glide.with(context)
                        .load(head + Config.IMAGE_LIM)
                        .dontAnimate()
                        .placeholder(R.mipmap.icon_no_head)
                        .into(headPhoto);
                name_tv.setText(name);
            }

            praise.setText(praiseNum);
            comment.setText(commentNum);
            timecha(timeTv, time);

            List<UserModel> list = new ArrayList<>();
            for (int i = 0; i < commentRemindJsonBean.getList().size(); i++) {
                UserModel userModel = new UserModel();
                userModel.setUser_name(commentRemindJsonBean.getList().get(i).getNickname());
                userModel.setUser_id(commentRemindJsonBean.getList().get(i).getUserId() + "");
                list.add(userModel);
            }
            //直接使用RichTextView
            content_tv.setAtColor(Color.parseColor(getString(R.string.remind_color)));
            content_tv.setLinkColor(Color.BLUE);
            content_tv.setSpanAtUserCallBackListener(spanAtUserCallBack);
            //所有配置完成后才设置text
            if (weight == 1) {
                content_tv.setRichTextUser("[icon_comment_official] " + content, list);
            } else if (weight == 2) {
                content_tv.setRichTextUser("[icon_comment_god] " + content, list);
            } else {
                content_tv.setRichTextUser(content, list);
            }

            if ("0".equals(isLike)) {
                praise.setCompoundDrawablesWithIntrinsicBounds(drawable_unselect, null, null, null);
            } else {
                praise.setCompoundDrawablesWithIntrinsicBounds(drawable_select, null, null, null);
            }

            if ((mUserInfoBean.getUser().getUserId() + "").equals(content_userid)) {
                detail_more.setVisibility(View.VISIBLE);
            } else if ((mUserInfoBean.getUser().getUserId() + "").equals(userId)) {
                detail_more.setVisibility(View.VISIBLE);
            } else {
                detail_more.setVisibility(View.INVISIBLE);
            }

        }

        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        refreshLayout.setEnableAutoLoadMore(true);

        quickAdapter = new QuickAdapter<CommentListBean.PageBean.ListBean>(context, R.layout.item_comment_receive) {
            @Override
            protected void convert(BaseAdapterHelper helper, CommentListBean.PageBean.ListBean item) {
                LinearLayout item_ll = helper.getView(R.id.item_ll);
                item_ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isDoubleClick()) {
                            return;
                        }
                        if ((mUserInfoBean.getUser().getUserId() + "").equals(userId + "")) {
                            deleteItemComment(item, "delete_report");
                        } else if ((mUserInfoBean.getUser().getUserId() + "").equals(content_userid + "")) {
                            deleteItemComment(item, "delete_report");
                        } else if ((mUserInfoBean.getUser().getUserId() + "").equals(item.getUserId() + "")) {
                            deleteItemComment(item, "delete");
                        } else {
                            deleteItemComment(item, "report");
                        }
                    }
                });
                item_ll.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        return true;
                    }
                });
                CircleImageView head_photo = helper.getView(R.id.head_photo);
                if ((item.getUserId() + "").equals(content_userid)) {
                    if (content_userid.equals(item.getReplyUserId() + "")) {
                        if ("1".equals(content_anonymity)) {
                            Glide.with(context)
                                    .load("")
                                    .dontAnimate()
                                    .error(R.mipmap.head_anonymous_purple)
                                    .into(head_photo);

                            head_photo.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                }
                            });

                            TextView name = helper.getView(R.id.name);

                            if (userId.equals(item.getUserId())) {
                                name.setText("匿名用户（主人回复）");
                            } else {
                                name.setText("匿名用户（主人回复）" + " 回复 " + "匿名用户（主人）");
                            }
                        } else {
                            Glide.with(context)
                                    .load(item.getAvatar() + Config.IMAGE_LIM)
                                    .dontAnimate()
                                    .error(R.mipmap.icon_no_head)
                                    .into(head_photo);

                            head_photo.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (Utils.isDoubleClick()) {
                                        return;
                                    }
                                    Bundle bundle1 = new Bundle();
                                    bundle1.putString("userId", item.getUserId() + "");
                                    bundle1.putString("userName", item.getNickname() + "");
                                    startActivity(OtherInfoActivity.class, bundle1);
                                }
                            });

                            TextView name = helper.getView(R.id.name);

                            if (userId.equals(item.getUserId())) {
                                name.setText(item.getNickname());
                            } else {
                                name.setText(item.getNickname() + " 回复 " + item.getReplyNickname());
                            }
                        }
                    } else {
                        if ("1".equals(content_anonymity)) {
                            Glide.with(context)
                                    .load("")
                                    .dontAnimate()
                                    .error(R.mipmap.head_anonymous_green)
                                    .into(head_photo);

                            head_photo.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                }
                            });

                            TextView name = helper.getView(R.id.name);

                            if (userId.equals(item.getUserId())) {
                                name.setText("匿名用户（主人回复）");
                            } else {
                                name.setText("匿名用户（主人回复）" + " 回复 " + item.getReplyNickname());
                            }
                        } else {
                            Glide.with(context)
                                    .load(item.getAvatar() + Config.IMAGE_LIM)
                                    .dontAnimate()
                                    .error(R.mipmap.icon_no_head)
                                    .into(head_photo);

                            head_photo.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (Utils.isDoubleClick()) {
                                        return;
                                    }
                                    Bundle bundle1 = new Bundle();
                                    bundle1.putString("userId", item.getUserId() + "");
                                    bundle1.putString("userName", item.getNickname() + "");
                                    startActivity(OtherInfoActivity.class, bundle1);
                                }
                            });

                            TextView name = helper.getView(R.id.name);

                            if (userId.equals(item.getUserId())) {
                                name.setText(item.getNickname());
                            } else {
                                name.setText(item.getNickname() + " 回复 " + item.getReplyNickname());
                            }
                        }
                    }
                } else {
                    if (content_userid.equals(item.getReplyUserId() + "")) {
                        if ("1".equals(content_anonymity)) {
                            Glide.with(context)
                                    .load(item.getAvatar() + Config.IMAGE_LIM)
                                    .dontAnimate()
                                    .error(R.mipmap.icon_no_head)
                                    .into(head_photo);

                            head_photo.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (Utils.isDoubleClick()) {
                                        return;
                                    }
                                    Bundle bundle1 = new Bundle();
                                    bundle1.putString("userId", item.getUserId() + "");
                                    bundle1.putString("userName", item.getNickname() + "");
                                    startActivity(OtherInfoActivity.class, bundle1);
                                }
                            });

                            TextView name = helper.getView(R.id.name);

                            if (userId.equals(item.getUserId())) {
                                name.setText(item.getNickname());
                            } else {
                                name.setText(item.getNickname() + " 回复 " + "匿名用户（主人）");
                            }
                        } else {
                            Glide.with(context)
                                    .load(item.getAvatar() + Config.IMAGE_LIM)
                                    .dontAnimate()
                                    .error(R.mipmap.icon_no_head)
                                    .into(head_photo);

                            head_photo.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (Utils.isDoubleClick()) {
                                        return;
                                    }
                                    Bundle bundle1 = new Bundle();
                                    bundle1.putString("userId", item.getUserId() + "");
                                    bundle1.putString("userName", item.getNickname() + "");
                                    startActivity(OtherInfoActivity.class, bundle1);
                                }
                            });

                            TextView name = helper.getView(R.id.name);

                            if (userId.equals(item.getUserId())) {
                                name.setText(item.getNickname());
                            } else {
                                name.setText(item.getNickname() + " 回复 " + item.getReplyNickname());
                            }
                        }
                    } else {
                        Glide.with(context)
                                .load(item.getAvatar() + Config.IMAGE_LIM)
                                .dontAnimate()
                                .error(R.mipmap.icon_no_head)
                                .into(head_photo);

                        head_photo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Utils.isDoubleClick()) {
                                    return;
                                }
                                Bundle bundle1 = new Bundle();
                                bundle1.putString("userId", item.getUserId() + "");
                                bundle1.putString("userName", item.getNickname() + "");
                                startActivity(OtherInfoActivity.class, bundle1);
                            }
                        });

                        TextView name = helper.getView(R.id.name);

                        if (userId.equals(item.getUserId())) {
                            name.setText(item.getNickname());
                        } else {
                            name.setText(item.getNickname() + " 回复 " + item.getReplyNickname());
                        }
                    }
                }


                RichTextView content = helper.getView(R.id.content);
                content.setMaxLines(Integer.MAX_VALUE);
                List<UserModel> list = new ArrayList<>();
                if (!TextUtils.isEmpty(item.getRemindJson()) && !"[]".equals(item.getRemindJson())) {
                    List<RemindJson> remindJsons = GsonUtil.jsonToList(item.getRemindJson(), RemindJson.class);
                    if (remindJsons != null) {
                        for (int i = 0; i < remindJsons.size(); i++) {
                            UserModel userModel = new UserModel();
                            userModel.setUser_name(remindJsons.get(i).getNickname());
                            userModel.setUser_id(remindJsons.get(i).getUserId() + "");
                            list.add(userModel);
                        }
                    }
                }
                //直接使用RichTextView
                content.setAtColor(Color.parseColor(getString(R.string.remind_color)));
                content.setLinkColor(Color.BLUE);
                content.setSpanAtUserCallBackListener(spanAtUserCallBack);
                //所有配置完成后才设置text
                content.setRichTextUser(item.getComment(), list);

                TextView praise = helper.getView(R.id.praise);
                if (item.getIsLike() == 0) {
                    praise.setCompoundDrawablesWithIntrinsicBounds(drawable_unselect, null, null, null);
                } else {
                    praise.setCompoundDrawablesWithIntrinsicBounds(drawable_select, null, null, null);
                }
                praise.setText(item.getLikeSum() + "");
                praise.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isDoubleClick()) {
                            return;
                        }
                        if (item.getIsLike() == 1) {
                            praise.setEnabled(false);
                            showDialog(context, "取消中...");
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("contentId", item.getId());
                                if (!TextUtils.isEmpty(module) && "2".equals(module)) {
                                    jsonObject.put("module", 2);
                                } else {
                                    jsonObject.put("module", 1);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.COMMENT_CANCEL_PRAISE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                @Override
                                public void onSuccess(SendCodeBean sendCodeBean) {
                                    dismissDialog();
                                    praise.setEnabled(true);
                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                        item.setIsLike(0);
                                        item.setLikeSum(item.getLikeSum() - 1);
                                        quickAdapter.notifyDataSetChanged();
                                    } else {
                                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                        } else {
                                            showImageToas(sendCodeBean.getMsg());
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    dismissDialog();
                                    praise.setEnabled(true);
                                }
                            });
                        } else {
                            praise.setEnabled(false);
                            showDialog(context, "点赞中...");
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("contentId", item.getId());
                                if (!TextUtils.isEmpty(module) && "2".equals(module)) {
                                    jsonObject.put("module", 2);
                                } else {
                                    jsonObject.put("module", 1);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.COMMENT_PRAISE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                @Override
                                public void onSuccess(SendCodeBean sendCodeBean) {
                                    dismissDialog();
                                    praise.setEnabled(true);
                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                        item.setIsLike(1);
                                        item.setLikeSum(item.getLikeSum() + 1);
                                        quickAdapter.notifyDataSetChanged();
                                    } else {
                                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                        } else {
                                            showImageToas(sendCodeBean.getMsg());
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    dismissDialog();
                                    praise.setEnabled(true);
                                }
                            });
                        }
                    }
                });


                TextView comment = helper.getView(R.id.comment);
                comment.setText("");
                comment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isDoubleClick()) {
                            return;
                        }
                        replyUserId = item.getUserId() + "";
                        replyCommentId_ = replyCommentId;
                        if ((item.getUserId() + "").equals(content_userid)) {
                            if ("1".equals(content_anonymity)) {
                                replayName = "匿名用户";
                                replayContent = item.getComment();
                            } else {
                                replayName = item.getNickname();
                                replayContent = item.getComment();
                            }
                        } else {
                            replayName = item.getNickname();
                            replayContent = item.getComment();
                        }
                        tokenVerify();
                    }
                });

                TextView time = helper.getView(R.id.time);
                timecha(item.getCreateTime(), time);
            }
        };

        receiveListview.setAdapter(quickAdapter);
        receiveListview.setFocusable(false);

    }

    @Override
    protected void initData() {
        showDialog(this, null);
        HttpParams params = new HttpParams();
        params.put("contentId", contentId);
        if (!TextUtils.isEmpty(module) && "2".equals(module)) {
            params.put("type", 2);
        } else {
            params.put("type", 1);
        }
        params.put("position", 2);
        if (mUserInfoBean != null) {
            params.put("userId", mUserInfoBean.getUser().getUserId());
        }
        params.put("replyCommentId", replyCommentId);
        params.put("limit", pageSize);
        params.put("page", pageNum++);
        finalOkGo.request(RequestType.POST, Url.GET_COMMENT_LIST, params, Url.GET_COMMENT_LIST, new Callback<CommentListBean>() {
            @Override
            public void onSuccess(CommentListBean commentListBean) {
                dismissDialog();
                if (commentListBean.getCode() == Contacts.SUCCESS) {
                    if (pageNum - 1 == 1) {
                        quickAdapter.clear();
                        quickAdapter.addAll(commentListBean.getPage().getList());
                    } else {
                        quickAdapter.addAll(commentListBean.getPage().getList());
                    }

                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    quickAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (commentListBean.getPage().getTotalCount() % pageSize == 0) {
                        pagecount = commentListBean.getPage().getTotalCount() / pageSize;
                    } else {
                        pagecount = commentListBean.getPage().getTotalCount() / pageSize + 1;
                    }

                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }

                } else {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    if (commentListBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(commentListBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
            }
        });
    }

    private long formattingtime;
    private long TimeCha;

    private void timecha(String startime, TextView textView) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dataformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long currenttime = calendar.getTimeInMillis();//获取系统当先时间的毫秒值
        try {//如果你的初始时间是格式化过的,则需要先转化成毫秒值
            formattingtime = dataformat.parse(startime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
//这里需要注意,因为获取的时间因为时差的缘故已经自动加上了8小时的时间,所以这里需要减去.如果不减去,就算是你刚刚发布的动态也会显示是8小时之前
        TimeCha = ((currenttime - formattingtime) / 1000) /*- (8 * 60 * 60)*/;//将毫秒值转化成分钟数
//        Logger.e(TimeCha+"");
        if (TimeCha < 60) {
            textView.setText("刚刚");
        } else if (TimeCha >= 60 && TimeCha < 3600) {
            textView.setText(TimeCha / 60 + "分钟前");
        } else if (TimeCha >= 3600 && TimeCha < 3600 * 24) {
            textView.setText(TimeCha / 3600 + "小时前");
        } else if (TimeCha >= 3600 * 1 * 24 && TimeCha < 3600 * 31 * 24) {
            textView.setText(TimeCha / 3600 / 24 + "天前");
        } else if (TimeCha >= 3600 * 31 * 24 * 1 && TimeCha < 3600 * 31 * 24 * 12) {
            textView.setText(TimeCha / 3600 / 24 / 30 + "个月前");
        } else {
            textView.setText(TimeCha / 3600 / 24 / 30 / 12 + "年前");
        }
    }

    //    @Override
    @OnClick({R.id.comment_et, R.id.detail_more, R.id.head_photo, R.id.praise, R.id.comment, R.id.watch, R.id.send/*, R.id.fragment_container*/})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.detail_more:
                if ((mUserInfoBean.getUser().getUserId() + "").equals(content_userid)) {
                    deleteComment("delete_report");
                } else if ((mUserInfoBean.getUser().getUserId() + "").equals(userId)) {
                    deleteComment("delete");
                } else {
                    deleteComment("report");
                }
                break;
            case R.id.head_photo:
                if (content_userid.equals(userId)) {
                    if (!"1".equals(content_anonymity)) {
                        Bundle bundle1 = new Bundle();
                        bundle1.putString("userId", userId);
                        bundle1.putString("userName", name);
                        startActivity(OtherInfoActivity.class, bundle1);
                    } else {
                        showImageToas("匿名用户无法查看主页");
                    }
                } else {
                    Bundle bundle1 = new Bundle();
                    bundle1.putString("userId", userId);
                    bundle1.putString("userName", name);
                    startActivity(OtherInfoActivity.class, bundle1);
                }
                break;
            case R.id.praise:
                if ("1".equals(isLike)) {
                    praise.setEnabled(false);
                    showDialog(context, "取消中...");
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("contentId", replyCommentId);
                        if (!TextUtils.isEmpty(module) && "2".equals(module)) {
                            jsonObject.put("module", 2);
                        } else {
                            jsonObject.put("module", 1);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.COMMENT_CANCEL_PRAISE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                        @Override
                        public void onSuccess(SendCodeBean sendCodeBean) {
                            dismissDialog();
                            praise.setEnabled(true);
                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                isLike = "0";
                                praise.setText(Integer.parseInt(praise.getText().toString()) - 1 + "");
                                praise.setCompoundDrawablesWithIntrinsicBounds(drawable_unselect, null, null, null);
//                                EventBus.getDefault().post("commentDetail_refresh");
                                EventBus.getDefault().post("refresh_cancel_praise_comment_count:" + id);
                            } else {
                                if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                } else {
                                    showImageToas(sendCodeBean.getMsg());
                                }
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                            praise.setEnabled(true);
                        }
                    });
                } else {
                    praise.setEnabled(false);
                    showDialog(context, "点赞中...");
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("contentId", replyCommentId);
                        if (!TextUtils.isEmpty(module) && "2".equals(module)) {
                            jsonObject.put("module", 2);
                        } else {
                            jsonObject.put("module", 1);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.COMMENT_PRAISE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                        @Override
                        public void onSuccess(SendCodeBean sendCodeBean) {
                            dismissDialog();
                            praise.setEnabled(true);
                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                isLike = "1";
                                praise.setText(Integer.parseInt(praise.getText().toString()) + 1 + "");
                                praise.setCompoundDrawablesWithIntrinsicBounds(drawable_select, null, null, null);
//                                EventBus.getDefault().post("commentDetail_refresh");
                                EventBus.getDefault().post("refresh_praise_comment_count:" + id);
                            } else {
                                if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                } else {
                                    showImageToas(sendCodeBean.getMsg());
                                }
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                            praise.setEnabled(true);
                        }
                    });
                }
                break;
            case R.id.comment:
                replyUserId = userId;
                replyCommentId_ = replyCommentId;
                if (content_userid.equals(userId)) {
                    if ("1".equals(content_anonymity)) {
                        replayName = "匿名用户";
                        replayContent = content;
                    } else {
                        replayName = name;
                        replayContent = content;
                    }
                } else {
                    replayName = name;
                    replayContent = content;
                }
                tokenVerify();
                break;
            case R.id.watch:
                finishActivity();
                break;
            case R.id.send:
                replyUserId = userId;
                replyCommentId_ = replyCommentId;
                if (content_userid.equals(userId)) {
                    if ("1".equals(content_anonymity)) {
                        replayName = "匿名用户";
                        replayContent = content;
                    } else {
                        replayName = name;
                        replayContent = content;
                    }
                } else {
                    replayName = name;
                    replayContent = content;
                }
                tokenVerify();
                break;
            case R.id.comment_et:
                replyUserId = userId;
                replyCommentId_ = replyCommentId;
                if (content_userid.equals(userId)) {
                    if ("1".equals(content_anonymity)) {
                        replayName = "匿名用户";
                        replayContent = content;
                    } else {
                        replayName = name;
                        replayContent = content;
                    }
                } else {
                    replayName = name;
                    replayContent = content;
                }
                tokenVerify();
                break;
        }
    }

    private void deleteItemComment(CommentListBean.PageBean.ListBean item, String flag) {
        DialogUtil.getInstance().showCenterDialog(context, R.layout.dialog_more);
        LinearLayout dialog_more = (LinearLayout) DialogUtil.getInstance().dialog_center_layout;
        LinearLayout cancel_follow = dialog_more.findViewById(R.id.cancel_follow);
        LinearLayout delete = dialog_more.findViewById(R.id.delete);
        LinearLayout report = dialog_more.findViewById(R.id.report);
        LinearLayout black_list = dialog_more.findViewById(R.id.black_list);
        LinearLayout receive = dialog_more.findViewById(R.id.receive);

        TextView delete_tv = dialog_more.findViewById(R.id.delete_tv);
        TextView report_tv = dialog_more.findViewById(R.id.report_tv);

        delete_tv.setText("删除该评论");
        report_tv.setText("举报该评论");

        View line = dialog_more.findViewById(R.id.line);
        View viewline = dialog_more.findViewById(R.id.view);
        View view1 = dialog_more.findViewById(R.id.view1);
        View view2 = dialog_more.findViewById(R.id.view2);

        if (flag.equals("delete_report")) {
            report.setVisibility(View.VISIBLE);
            black_list.setVisibility(View.GONE);
            cancel_follow.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
            viewline.setVisibility(View.GONE);
            view1.setVisibility(View.VISIBLE);
            delete.setVisibility(View.VISIBLE);
            view2.setVisibility(View.VISIBLE);
            receive.setVisibility(View.VISIBLE);
        } else if ("report".equals(flag)) {
            report.setVisibility(View.VISIBLE);
            black_list.setVisibility(View.GONE);
            cancel_follow.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
            viewline.setVisibility(View.GONE);
            view1.setVisibility(View.INVISIBLE);
            delete.setVisibility(View.GONE);
            view2.setVisibility(View.VISIBLE);
            receive.setVisibility(View.VISIBLE);
        } else {
            report.setVisibility(View.GONE);
            black_list.setVisibility(View.GONE);
            cancel_follow.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
            viewline.setVisibility(View.GONE);
            view1.setVisibility(View.INVISIBLE);
            delete.setVisibility(View.VISIBLE);
            view2.setVisibility(View.VISIBLE);
            receive.setVisibility(View.VISIBLE);
        }

        receive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                DialogUtil.getInstance().dialog_center.dismiss();
                replyUserId = item.getUserId() + "";
                replyCommentId_ = replyCommentId;
                if ((item.getUserId() + "").equals(content_userid)) {
                    if ("1".equals(content_anonymity)) {
                        replayName = "匿名用户";
                        replayContent = item.getComment();
                    } else {
                        replayName = item.getNickname();
                        replayContent = item.getComment();
                    }
                } else {
                    replayName = item.getNickname();
                    replayContent = item.getComment();
                }
                tokenVerify();
            }
        });

        report.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                DialogUtil.getInstance().dialog_center.dismiss();
                Bundle bundle = new Bundle();
                bundle.putString("flag", "report");
                bundle.putString("contentId", contentId + "");
                if (!TextUtils.isEmpty(module) && "2".equals(module)) {
                    bundle.putString("module", "2");
                } else {
                    bundle.putString("module", "1");
                }
                bundle.putString("type", "2");
                bundle.putString("byUserId", item.getUserId() + "");
                bundle.putString("commentId", item.getId() + "");
                startActivity(ReportActivity.class, bundle);
            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                DialogUtil.getInstance().dialog_center.dismiss();
                showDialog(context, "删除中...");
                HttpParams params = new HttpParams();
                params.put("commentId", item.getId());
                finalOkGo.requestHead(RequestType.POSTHEAD, Url.DELETE_COMMENT, params, Url.DELETE_COMMENT, new Callback<SendCodeBean>() {
                    @Override
                    public void onSuccess(SendCodeBean sendCodeBean) {
                        dismissDialog();
                        if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                            EventBus.getDefault().post("comment_detial_sub");
                            EventBus.getDefault().post("comment_detial_sub_home:" + contentId);
                            comment.setText((Integer.parseInt(comment.getText().toString()) - 1) + "");
                            quickAdapter.remove(item);
                            quickAdapter.notifyDataSetChanged();
                        } else {
                            if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                            } else {
                                showImageToas(sendCodeBean.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
            }
        });
    }

    private void deleteComment(String flag) {
        DialogUtil.getInstance().showCenterDialog(context, R.layout.dialog_more);
        LinearLayout dialog_more = (LinearLayout) DialogUtil.getInstance().dialog_center_layout;
        LinearLayout cancel_follow = dialog_more.findViewById(R.id.cancel_follow);
        LinearLayout delete = dialog_more.findViewById(R.id.delete);
        LinearLayout report = dialog_more.findViewById(R.id.report);
        LinearLayout black_list = dialog_more.findViewById(R.id.black_list);
        LinearLayout receive = dialog_more.findViewById(R.id.receive);

        TextView delete_tv = dialog_more.findViewById(R.id.delete_tv);
        TextView report_tv = dialog_more.findViewById(R.id.report_tv);

        delete_tv.setText("删除该评论");
        report_tv.setText("举报该评论");

        View line = dialog_more.findViewById(R.id.line);
        View viewline = dialog_more.findViewById(R.id.view);
        View view1 = dialog_more.findViewById(R.id.view1);
        View view2 = dialog_more.findViewById(R.id.view2);

        if (flag.equals("delete_report")) {
            report.setVisibility(View.VISIBLE);
            black_list.setVisibility(View.GONE);
            cancel_follow.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
            viewline.setVisibility(View.GONE);
            view1.setVisibility(View.VISIBLE);
            delete.setVisibility(View.VISIBLE);
            view2.setVisibility(View.VISIBLE);
            receive.setVisibility(View.VISIBLE);
        } else if ("report".equals(flag)) {
            report.setVisibility(View.VISIBLE);
            black_list.setVisibility(View.GONE);
            cancel_follow.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
            viewline.setVisibility(View.GONE);
            view1.setVisibility(View.INVISIBLE);
            delete.setVisibility(View.GONE);
            view2.setVisibility(View.VISIBLE);
            receive.setVisibility(View.VISIBLE);
        } else {
            report.setVisibility(View.GONE);
            black_list.setVisibility(View.GONE);
            cancel_follow.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
            viewline.setVisibility(View.GONE);
            view1.setVisibility(View.INVISIBLE);
            delete.setVisibility(View.VISIBLE);
            view2.setVisibility(View.VISIBLE);
            receive.setVisibility(View.VISIBLE);
        }

        receive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                replyUserId = userId;
                replyCommentId_ = replyCommentId;
                if (content_userid.equals(userId)) {
                    if ("1".equals(content_anonymity)) {
                        replayName = "匿名用户";
                        replayContent = content;
                    } else {
                        replayName = name;
                        replayContent = content;
                    }
                } else {
                    replayName = name;
                    replayContent = content;
                }
                tokenVerify();
            }
        });

        report.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                DialogUtil.getInstance().dialog_center.dismiss();
                Bundle bundle = new Bundle();
                bundle.putString("flag", "report");
                bundle.putString("contentId", contentId + "");
                if (!TextUtils.isEmpty(module) && "2".equals(module)) {
                    bundle.putString("module", "2");
                } else {
                    bundle.putString("module", "1");
                }
                bundle.putString("type", "2");
                bundle.putString("byUserId", userId + "");
                bundle.putString("commentId", id + "");
                startActivity(ReportActivity.class, bundle);
            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                DialogUtil.getInstance().dialog_center.dismiss();
                showDialog(context, "删除中...");
                HttpParams params = new HttpParams();
                params.put("commentId", id);
                finalOkGo.requestHead(RequestType.POSTHEAD, Url.DELETE_COMMENT, params, Url.DELETE_COMMENT, new Callback<SendCodeBean>() {
                    @Override
                    public void onSuccess(SendCodeBean sendCodeBean) {
                        dismissDialog();
                        if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                            EventBus.getDefault().post("comment_detial_sub:" + content);
                            EventBus.getDefault().post("comment_detial_sub_home_content:" + contentId + ":" + content);
                            finishActivity();
                        } else {
                            if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                            } else {
                                showImageToas(sendCodeBean.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
            }
        });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        initData();
    }


    private void tokenVerify() {
        HttpParams params = new HttpParams();
        params.put("token", (String) SharedPreferencesHelp.get("token", ""));
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.VERIFY_TOKEN, params, Url.VERIFY_TOKEN, new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                    DetailCommentDialog commentDialogFragment = new DetailCommentDialog();
                    commentDialogFragment.setCommentFlag("CommentDetailActivity");
                    commentDialogFragment.show(getFragmentManager(), "DetailCommentDialog");
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
            }
        });
    }

    @Override
    public String getCommentText() {
        return comment_et.getText().toString();
    }

    @Override
    public String getReplayName() {
        return replayName;
    }

    @Override
    public String getReplayContent() {
        return replayContent;
    }

    @Override
    public void setCommentText(String commentTextTemp) {
        if(!TextUtils.isEmpty(commentTextTemp)){
            comment_et.setRichText(commentTextTemp);
        }else{
            comment_et.setText(commentTextTemp);
        }
    }

    @Override
    public List<UserModel> getNameList() {
        for (int i = 0; i < comment_et.getNameList().size(); i++) {
            comment_et.getNameList().get(i).setUser_name("@" + comment_et.getNameList().get(i).getUser_name());
        }
        return comment_et.getNameList();
    }

    @Override
    public void setNameList(List<UserModel> nameList) {
        comment_et.setNameList(nameList);
    }
}
